package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.security.auth.callback.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 代码清单-p3ch13a-410页a：CallbackHandler接口的实现类的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/7 18:27
 */
public class TextCallbackHandler implements CallbackHandler {

    private static final Logger logger = LogManager.getLogger(TextCallbackHandler.class);

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (Callback callback: callbacks) {
            if (callback instanceof TextInputCallback) {
                TextInputCallback textInputCallback = (TextInputCallback) callback;
                logger.info("....TextInputCallback#Prompt:{}...", textInputCallback.getPrompt());
                textInputCallback.setText((new BufferedReader(new InputStreamReader(System.in))).readLine());
             } else if (callback instanceof TextOutputCallback) {
                TextOutputCallback textOutputCallback = (TextOutputCallback) callback;
                String messageType = "";
                switch (textOutputCallback.getMessageType()) {
                    case TextOutputCallback.INFORMATION:
                        messageType = "信息：";
                        break;
                    case TextOutputCallback.WARNING:
                        messageType = "警告：";
                        break;
                    case TextOutputCallback.ERROR:
                        messageType = "错误：";
                        break;
                }

                logger.info("...获得的消息:{}...", messageType + textOutputCallback.getMessage());
            } else {
                throw new UnsupportedCallbackException(callback);
            }
        }
    }
}
